package org.smog.core.config.swagger;

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: Created by IntelliJ IDEA.
 * @project_name: smogTemp
 * @time: 2020-05-13 16:59
 * @email: 17685306043@163.com
 * @author: huangZhongYao
 */
@Slf4j
@Configuration
@EnableSwagger2
@EnableKnife4j
@AllArgsConstructor
public class SwaggerConfig {

	SwaggerProperties swaggerProperties;

	@Bean
	public Docket createRestApi() {
		log.info("Swagger 初始化配置... ");

		List<Parameter> parameters = new ArrayList<>();
		this.swaggerProperties.getParameter().forEach((k, param) -> {
			parameters.add(new ParameterBuilder()
					.name(param.name)
					.description(param.description)
					.modelRef(new ModelRef("string"))
					.parameterType(param.paramType)
					.required(param.required)
					.hidden(param.hidden)
					.order(param.order)
					.build());
		});

		return new Docket(DocumentationType.SWAGGER_2)
				.enable(swaggerProperties.enable)
				.pathMapping(swaggerProperties.basePath)
				.apiInfo(apiInfo())
				.select()
				.apis(RequestHandlerSelectors.basePackage(swaggerProperties.basePackage))
				.paths(PathSelectors.any())
				.build()
				.host(swaggerProperties.host)
				.groupName(swaggerProperties.groupName)
				.globalOperationParameters(parameters);
	}


	public ApiInfo apiInfo() {
		log.info("Swagger 完成初始化配置... ");
		return new ApiInfoBuilder()
				.title(swaggerProperties.title)
				.description(swaggerProperties.description)
				.version(swaggerProperties.version)
				.license(swaggerProperties.license)
				.licenseUrl(swaggerProperties.licenseUrl)
				.termsOfServiceUrl(swaggerProperties.termsOfServiceUrl)
				.contact(new Contact(swaggerProperties.getContact().name, swaggerProperties.getContact().url, swaggerProperties.getContact().email))
				.build();
	}
}
